import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart';
import 'package:xmshop/app/models/category_model.dart';
import 'package:xmshop/app/models/focus_model.dart';
import 'package:xmshop/app/models/plist_model.dart';
import 'package:xmshop/app/services/httpsClient.dart';

class HomeController extends GetxController {
  //TODO: Implement HomeController
  RxBool isGetOut = false.obs;

  final ScrollController scrollController = ScrollController();

  // 定义成响应式数据
  RxList<FocusItemModel> swiperList = <FocusItemModel>[].obs;
  RxList<FocusItemModel> bestSellingSwiperList = <FocusItemModel>[].obs;
  RxList<CategoryItemModel> categoryList = <CategoryItemModel>[].obs;
  RxList<PlistItemModel> sellingPlist = <PlistItemModel>[].obs;

  RxList<PlistItemModel> bestPlist = <PlistItemModel>[].obs;

  HttpsClient httpsClient = HttpsClient();

  @override
  void onInit() {
    super.onInit();

    // 请求数据
    getFocusData();
    //获取分类数据
    getCategoryData();
    //获取热销臻选里面的轮播图
    getSellingSwiperData();
    //获取热销臻选里面的商品
    getSellingPlistData();
    // 获取热门商品
    getBestPlistData();

    scrollController.addListener(() {
      // 滚出去了
      if (scrollController.position.pixels > 30) {
        if (isGetOut.value == false) {
          print("---滚出去了---");
          isGetOut.value = true;
          update();
        }
      }

      // 滚回来了
      if (scrollController.position.pixels < 30) {
        if (isGetOut.value == true) {
          print("---滚回来了---");
          isGetOut.value = false;
          update();
        }
      }
    });
  }

  @override
  void onClose() {
    super.onClose();
  }

  getFocusData() async {
    var response = await Dio().get("https://xiaomi.itying.com/api/focus");

    var focus = FocusModel.fromJson(response.data);
    swiperList.value = focus.result!;

    update();
  }

  getCategoryData() async {
    var response = await Dio().get("https://xiaomi.itying.com/api/bestCate");

    var category = CategoryModel.fromJson(response.data);
    categoryList.value = category.result!;

    update();
  }

  //获取热销臻选里面的轮播图
  getSellingSwiperData() async {
    var response =
        await Dio().get("https://xiaomi.itying.com/api/focus?position=2");
    var sellingSwiper = FocusModel.fromJson(response.data);
    bestSellingSwiperList.value = sellingSwiper.result!;
    update();
  }

  //获取热销臻选里面的商品数据
  getSellingPlistData() async {
    var response = await Dio()
        .get("https://xiaomi.itying.com/api/plist?is_hot=1&pageSize=3");
    var plist = PlistModel.fromJson(response.data);
    sellingPlist.value = plist.result!;
    update();
  }

  // 获取热门商品数据
  getBestPlistData() async {
    var response = await httpsClient.get("api/plist?is_best=1");
    if (response != null) {
      var plist = PlistModel.fromJson(response.data);
      bestPlist.value = plist.result!;

      update();
    }
  }
}
